package com.teaching.management.controller.api;

import com.teaching.management.entity.Student;
import com.teaching.management.entity.User;
import com.teaching.management.repository.StudentRepository;
import com.teaching.management.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 学生管理相关的REST API
 */
@RestController
@RequestMapping("/api/admin/students")
public class AdminStudentRestController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取所有学生
     */
    @GetMapping
    public ResponseEntity<?> getAllStudents(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        List<Student> students = studentRepository.findAll();
        return ResponseEntity.ok(students);
    }

    /**
     * 根据条件搜索学生
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchStudents(@RequestParam("term") String searchTerm, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 创建模糊匹配，匹配学生学号或姓名
        Student example = new Student();
        example.setStudentId(searchTerm);
        example.setName(searchTerm);

        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        List<Student> students = studentRepository.findAll(Example.of(example, matcher));
        return ResponseEntity.ok(students);
    }

    /**
     * 获取单个学生详情
     */
    @GetMapping("/{studentId}")
    public ResponseEntity<?> getStudent(@PathVariable String studentId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        Optional<Student> studentOpt = studentRepository.findById(studentId);
        if (studentOpt.isPresent()) {
            return ResponseEntity.ok(studentOpt.get());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生不存在");
        }
    }

    /**
     * 添加新学生
     */
    @PostMapping
    @Transactional
    public ResponseEntity<?> addStudent(@RequestBody Map<String, Object> studentData, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 从请求中提取学生信息和用户信息
        String studentId = (String) studentData.get("studentId");
        String name = (String) studentData.get("name");
        String gender = (String) studentData.get("gender");
        String major = (String) studentData.get("major");
        String grade = (String) studentData.get("grade");
        String birthDate = (String) studentData.get("birthDate");
        String enrollmentDate = (String) studentData.get("enrollmentDate");
        String username = (String) studentData.get("username");
        String password = (String) studentData.get("password");

        // 检查学生ID是否已存在
        if (studentRepository.existsById(studentId)) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("学号已存在");
        }

        // 检查用户名是否已存在
        if (userRepository.findByUsernameAndPasswordAndRole(username, null, null) != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名已存在");
        }

        // 创建用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRole("学生");
        User savedUser = userRepository.save(newUser);

        // 创建学生
        Student student = new Student();
        student.setStudentId(studentId);
        student.setUserId(savedUser.getUserId());
        student.setName(name);
        student.setGender(gender);
        student.setMajor(major);
        student.setGrade(grade);
        student.setBirthDate(java.sql.Date.valueOf(birthDate));
        student.setEnrollmentDate(java.sql.Date.valueOf(enrollmentDate));

        Student savedStudent = studentRepository.save(student);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedStudent);
    }

    /**
     * 更新学生信息
     */
    @PutMapping("/{studentId}")
    public ResponseEntity<?> updateStudent(
            @PathVariable String studentId,
            @RequestBody Student student,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 确保路径中的ID与请求体中的ID一致
        if (!studentId.equals(student.getStudentId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("学号不一致");
        }

        // 检查学生是否存在
        if (!studentRepository.existsById(studentId)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生不存在");
        }

        Student updatedStudent = studentRepository.save(student);
        return ResponseEntity.ok(updatedStudent);
    }

    /**
     * 删除学生
     */
    @DeleteMapping("/{studentId}")
    @Transactional
    public ResponseEntity<?> deleteStudent(@PathVariable String studentId, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查学生是否存在
        Optional<Student> studentOpt = studentRepository.findById(studentId);
        if (!studentOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("学生不存在");
        }

        try {
            // 获取关联的用户ID
            Integer userId = studentOpt.get().getUserId();

            // 删除学生
            studentRepository.deleteById(studentId);

            // 删除关联的用户
            userRepository.deleteById(userId);

            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 可能因为外键约束而无法删除
            return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body("删除失败，该学生存在选课记录，请先解除关联");
        }
    }
}